// Window Resize Event

$(window).resize(function(){
	arrangeElements();
});

// Window Load Event

$(window).ready(function(){
	arrangeElements();
});

// Arrange Elements Cells

var arrangeElements = function(){

	// initialize temporal varuables
	var currentLeft = 0, currentTop = 5;
	var elements = $(".element-cell");
	var elementCount = elements.size();
	var cellsInRow = 0;
	var maxHeight = 0;
	var MARGIN_X = 8;
	var MARGIN_Y = -25;

	// arrange each cell
	for(var i=0; i<elementCount; i++){

		var target = elements.eq(i);

		// arrange cell for temporal
		target.css({"top":currentTop, "left":currentLeft});
		
		// when the cell were sticking out from the window, rearrange it on new line.
		// (If the cell is the only cell in the line, not rearrange.)
		if(currentLeft + target.width() > $(window).width() && cellsInRow > 0){
			currentTop += maxHeight + MARGIN_Y;
			currentLeft = 0;
			target.css({"top":currentTop, "left":currentLeft});
			cellsInRow = 1;
			maxHeight = target.height();
		} else {
			cellsInRow++;
			maxHeight = maxHeight > target.height() ? maxHeight : target.height();
		}
		currentLeft += target.width() + MARGIN_X;
			
	}
}
